/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
 import React, { Component } from 'react';
 import { Table, Form, Card, Tabs,Row, Col, Select,  DatePicker, } from 'antd';
 import '@/assets/css/settings';
 import * as Utils from '../../utils_yyr/action';
 import BasicForm from '../../components_yyr/common/basicFormbaobiao';
 import { FileDown } from '../../components_yyr/commponent/File';
 import Paging from '../../components_yyr/commponent/Paging';
 import Echarts from 'echarts-for-react';
//  import 'echarts-gl';
 import { euqApplicationName_gl } from '../../config';
 
 var date = new Date();
 let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
 let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
 let year = date.getFullYear()
 let todayEnd = `${year}-${month}-${day} 23:59:59`
 let todayStart = `${year}-${month}-01 00:00:00`
 let lastMonth = date.getMonth() ? `0${date.getMonth()}` : date.getMonth()
 let lastMonthStart = `${year}-${lastMonth}-01 00:00:00`
 const { TabPane } = Tabs;
 const { Option } = Select;
 const { MonthPicker, RangePicker, WeekPicker } = DatePicker
 class departmentAnalyse extends Component {
 
     state = {
         loading: false, //加载中...
         dataSource: [], //数据源
         drawerVisible: false, //新增修改抽屉的显示与隐藏
         chooseData: {}, //用checkbox选择好的数据
         total: 0, //总数据量
         formValues: {},
         weekList: [],
         value: '1',
         //  activeKey:'top',
         activeKey: 'top',
         panes: [],
         newTabIndex: 0,
         equipmentTypeChart: [],
         thisMonth: [], lastMonth: [], last90Day: [], dateString: [], UserList: [], EquTypeList: [],jjcd:[],wxlb:[]
     };
     constructor(props) {
         super(props);
         // console.log(props);
     }
     componentDidMount() {
         this.getDate()
         this.fetch({
             pageNum: 1,
             pageSize: 10,
            //  startTime:lastMonthStart,
            //  endTime:todayEnd,
         });
         this.EquipmentNextParameterPageList('jjcd',8)
         this.EquipmentNextParameterPageList('wxlb',7)
     }
     //初始化加载数据
     fetch = (data) => {
         let option1 = this.option1
         let str = ''
         console.log(data)
         this.setState({ loading: true, formValues: data},()=>{
             console.log(this.state.formValues)
         })
         for (var key in data) {
             if (data[key] || data[key] == 0) {
                 str += `&${key}=${data[key]}`
             }
         }
         this.get(`${euqApplicationName_gl}/equipmentMaintenanceReport/findStatisticalReport?${str}`).then(res => {
             let arr = res.data
             option1.dataset.source = arr
            //  console.log(arr)
            //  option1.xAxis.data = arr.map(item => item.repairTypeName.split(' ')[0])
            //  option1.series[0].data = arr.map(item => item.ywcCount)
            //  option1.series[1].data = arr.map(item => item.dwxCount)
            //  option1.series[2].data = arr.map(item => item.wxzCount)
             this.setState({ equipmentTypeChart: arr }, () => {
                 this.echartRef1.getEchartsInstance().setOption(option1, true);
             })
         })
         this.get(`${euqApplicationName_gl}/equipmentMaintenanceReport/findMaintenanceReportTable?${str}`).then(res => {
             this.setState({
                 loading: false,
                 dataSource: res.data.data,
                 total: res.data.total,
             });
         })
     }
 
    EquipmentNextParameterPageList = (data,type) => {//紧急程度列表
        this.get(`${euqApplicationName_gl}/api/findEquipmentNextParameterPageList?typeId=${type}`).then(res => {
            let obj = {}
            obj[data] = res.data
            this.setState(obj);
         })
    }; 
     getDate = () => {
         var date = new Date();
         let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
         let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
         let year = date.getFullYear()
         let todayEnd = `${year}-${month}-${day} 23:59:59`
         let todayStart = `${year}-${month}-01 00:00:00`
         let thisMonth = [todayStart, todayEnd]
         let lastMonth = this.getLastMonth()
         let last90Day = [this.getLast90Day(), todayEnd]
         this.setState({
             thisMonth, lastMonth, last90Day
         })
         // console.log(todayEnd,todayStart)
         // var dataList = [];
         // for (var i = 0; i < 3; i++) {
         //     var newDate = new Date(date);
         //     newDate.setMonth(date.getMonth() - i);
         //     dataList.unshift(`${newDate.getFullYear()}-${(newDate.getMonth() + 1).toString().padStart(2, '0')}`);
         // }
         // console.log(dataList)
         // console.log(this.getLastMonth())
         // console.log([this.getLast90Day(),todayEnd])
     }
     getLastMonth = () => {//获取上个月日期第一天
         var nowDate = new Date();
         var year = nowDate.getFullYear();
         var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
         if (month == 0) {
             year = year - 1;
             month = 12;
         }
         var lastDay = new Date(year, month, 0);
         var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
         var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
         return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
     }
     /**
      * 获取上个月月底日期
      */
     getLast90Day = () => {
         var nowDate = new Date();
         var year = nowDate.getFullYear();
         var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
         if (month == 0) {
             month = 12;
             year = year - 1;
         }
         var lastDay = new Date(year, month, 0);
         var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
         var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
         return yyyyMMdd;
     }
     getXianTiOption = () => {
         var colors = ['#5793f3', '#006699', '#4cabce'];
         var labelOption = {
             normal: {
                show: true,
                position: 'top',
           }
        }
         const option = {
            title:{
                text:'导出图片',
                show:false
            },
             color: colors,
             tooltip: {
                 trigger: 'axis',
                 axisPointer: {
                    type: 'shadow'
                 }
             },
             grid: {
                right: '2%',
                left: '2%',
                containLabel: true
             },
             toolbox: {
                 feature: {
                     // dataView: {show: true, readOnly: false},
                     // restore: {show: true},
                     saveAsImage: { show: true, title: '导出图' }
                 }
             },
             legend: {
                //  data: ['已完成', '待维修', '维修中']
             },
             dataset: {
                dimensions: ['repairTypeName', 'ywcCount', 'dwxCount', 'wxzCount'],
                source: []
            },
             xAxis: {
                 type: 'category',
             },
             yAxis: {},
             series: [
                 {
                     name: '已完成',
                    //  data: [],
                     type: 'bar',
                     barWidth: 50,
                     label: labelOption
                 },
                 {
                     name: '待维修',
                    //  data: [],
                     type: 'bar',
                     barWidth: 50,
                     label: labelOption
                 },
                 {
                     name: '维修中',
                    //  data: [],
                     type: 'bar',
                     barWidth: 50,
                     label: labelOption
                 },
             ],
             dataZoom: [
                 {
                     type: 'inside',
                     show: true,
                     xAxisIndex: [0],
                     // 缩放的开始位置的百分比，0 - 100
                     start: 1,
                     // 缩放的结束位置的百分比，0 - 100
                     end: 100,
                     // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                     // startValue?: number,
                     // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                     // endValue?: number
                 }
             ]
         };
         this.option1 = option
         return option;
     };
 
     onChangeTabs = activeKey => {
         console.log(activeKey)
         this.setState({ activeKey });
     };
 
     onEdit = (targetKey, action) => {
         this[action](targetKey);
     };
 
     //表单查询
     filterSubmit = values => {
         console.log(values)
         values.startTime = values.startTime_endTime && values.startTime_endTime.length===2 ? Utils.getDate(values.startTime_endTime[0]) +' 00:00:00' : ''
         values.endTime = values.startTime_endTime && values.startTime_endTime.length===2 ? Utils.getDate(values.startTime_endTime[1])+' 23:59:59' : ''
         delete values['startTime_endTime']
         let data = { ...this.state.formValues, ...values }
         console.log(data)
         this.fetch(data);
     };
     //头部关键字查询部分
     formList = () => {
         const { wxlb,jjcd } = this.state;
         const formList = [
            //  { type: "DATE", label: "发生时间", field: "startTime", allowClear: true}, 
            //  {type: 'DATE', label: '至', field: 'endTime', allowClear: true,placeholder:'请选择结束时间'},
             { type: "TIMEFRAME", label: "时间", field: "startTime_endTime", allowClear: true },
             {type: 'SELECT', label: '紧急程度', field: 'urgencyId',name: 'configValue', valueField: 'id', allowClear: true,list:jjcd},
             {type: 'SELECT', label: '维修类别', field: 'repairType',name: 'configValue', valueField: 'id', allowClear: true,list:wxlb},
             {type: 'INPUT', label: '设备名称', field: 'equName', allowClear: true},
     ];
         return formList;
     };
 
     onRowClick = (record) => {
         let data = this.state.formValues1
         data.planCode = record.planCode
         this.findInspectionRecordTable(data)
     }
     render() {
         const { chooseData, dataSource, loading, total, formValues ,} = this.state;
         const mergeCells = (text, array, columns) => {
            const temp = {}; // 当前重复的值,支持多列
            let i = 0;
            if (text !== temp[columns]) {
              temp[columns] = text;
              
              array.forEach((item) => {
                if (item[columns] === temp[columns]) {
                  i += 1;
                }
              });
            }
            return i;
          };
         const columns = [
             // { title: '序号', width: 100, dataIndex: 'id' },
             { title: '维修类别', width: 100, dataIndex: 'repairTypeName',
             render: (text, record, index) => {
                const obj = {
                  children: text,
                  props: {},
                };
                // 如果上面有相同的数据，如商品ID 222, 则rowSpan = 0
                if ((index > 0 && text !== dataSource[index - 1].repairTypeName) || index == 0) {
                  obj.props.rowSpan = mergeCells(record.repairTypeName, dataSource, 'repairTypeName')   
              } else {
                  obj.props.rowSpan = 0;
              }
      
                return obj;
              }, align:'center'},
             { title: '日期', width: 100, dataIndex: 'createTime',align:'center' },
             { title: '维修单号', width: 100, dataIndex: 'equRepairCode' ,align:'center'},
             { title: '状态', width: 100, dataIndex: 'statusName' ,align:'center'},
             { title: '设备编号', width: 100, dataIndex: 'equCode' ,align:'center'},
             { title: '设备名称', width: 100, dataIndex: 'equName' ,align:'center'},
             { title: '紧急程度', width: 100, dataIndex: 'urgency',align:'center' },
             { title: '计划', width: 100, dataIndex: 'isPlan',align:'center' },
             { title: '主修人员', width: 100, dataIndex: 'majorStaff',align:'center'},
             { title: '辅修人员', width: 100, dataIndex: 'minorStaff' ,align:'center'},
             { title: '计划(人*时*天)', width: 100, dataIndex: 'plan',align:'center' },
             { title: '总计划工时', width: 100, dataIndex: 'totalWorkHours' ,align:'center'},
             { title: '实际工时', width: 100, dataIndex: 'actualTime',align:'center' },
             { title: '外协工时', width: 100, dataIndex: 'outsourcingHours' ,align:'center'},
             { title: '维修费用', width: 100, dataIndex: 'maintenanceCosts' ,align:'center'},
             { title: '备注', width: 100, dataIndex: 'remarks',align:'center' },

         ]
         return (
             <div className="shadow-radius">
                 <Tabs hideAdd
                     onChange={this.onChangeTabs}
                     activeKey={this.state.activeKey}
                     type="editable-card"
                     onEdit={this.onEdit}>
                     <TabPane tab="维修分类统计" key="top" closable={false}>
                         <Card>
                             <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                         </Card>
                         <div>
                             <Tabs defaultActiveKey="1">
                                 <TabPane tab="统计图表" key="1" forceRender>
                                     <div style={{ display: 'flex' }}>
                                         <Echarts
                                             option={this.getXianTiOption()}
                                             style={{ width: '100%', height: '460px' }}
                                             ref={(e) => { this.echartRef1 = e; }}
                                         />
                                     </div>
                                 </TabPane>
                             </Tabs>
                         </div>
                         <div>
                            <Row>
                                <Col style={{ float: 'right' }}><FileDown fileName="维修分类统计报表" buttonName="导出表" method="post" apiPath={`${euqApplicationName_gl}/equipmentMaintenanceReport/importMaintenanceReportTableExcel`} data={{...this.state.formValues}} /></Col>
                            </Row>
                        </div>
                         <Table columns={columns} rowKey={(record, index) => index} dataSource={dataSource} pagination={false} loading={loading} bordered={true} scroll={{ x: 'calc(700px + 50%)' }}/>
                         <Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} />
                     </TabPane>
                 </Tabs>
             </div>
         );
     }
 }
 export default Form.create()(departmentAnalyse);
 